package com.example.project.controller.project;

import java.util.Arrays;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.project.core.controller.BaseController;
import com.example.project.core.domain.AjaxResult;
import com.example.project.entity.IssueComment;
import com.example.project.service.IssueCommentService;

/**
 * 需求评论控制器
 */
@Controller
@RequestMapping("/project/issue/comment")
public class IssueCommentController extends BaseController {
    
    private String prefix = "pm/issue";
    
    @Autowired
    private IssueCommentService commentService;
    
    /**
     * 查询需求评论列表
     */
    @RequiresPermissions("project:issue:view")
    @PostMapping("/list/{issueId}")
    @ResponseBody
    public AjaxResult list(@PathVariable Long issueId) {
        IssueComment comment = new IssueComment();
        comment.setIssueId(issueId);
        List<IssueComment> list = commentService.selectCommentsByIssueId(issueId, false);
        return success(list);
    }
    
    /**
     * 新增需求评论
     */
    @RequiresPermissions("project:comment:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult add(IssueComment comment) {
        // 设置当前用户
        comment.setAuthorId(getUserId());
        
        // 确定需要通知的用户
        // 这里可以添加更复杂的逻辑，比如通知需求创建者、处理者等
        List<Long> notifiedUsers = determineNotifiedUsers(comment.getIssueId(), getUserId());
        
        boolean result = commentService.addCommentWithNotification(comment, notifiedUsers);
        return result ? success() : error("添加评论失败");
    }
    
    /**
     * 修改需求评论
     */
    @RequiresPermissions("project:comment:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult edit(Long id,String content) {
		// 验证评论是否属于当前用户
		IssueComment comment = commentService.selectIssueCommentById(id);
		if (comment == null) {
			return error("评论不存在");
		}

		if (!comment.getAuthorId().equals(getUserId())) {
			return error("无权限修改此评论");
		}
		comment.setContent(content);

		return toAjax(commentService.updateIssueComment(comment));
	}
    
    /**
     * 删除需求评论
     */
    @RequiresPermissions("project:comment:remove")
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        // 验证评论是否属于当前用户或管理员
        String[] idArray = ids.split(",");
        for (String idStr : idArray) {
            Long id = Long.parseLong(idStr);
            IssueComment comment = commentService.selectIssueCommentById(id);
            if (comment == null) {
                continue;
            }
            
            if (!comment.getAuthorId().equals(getUserId()) && !getUser().isAdmin()) {
                return error("无权限删除此评论");
            }
        }
        
        return toAjax(commentService.deleteIssueCommentByIds(Arrays.stream(idArray).map(Long::parseLong).toArray(Long[]::new)));
    }
    
    /**
     * 加载评论区域
     */
    @GetMapping("/view/{issueId}")
    public String view(@PathVariable Long issueId, ModelMap mmap) {
        mmap.put("issueId", issueId);
        return prefix + "/comment_section";
    }
    
    /**
     * 确定需要通知的用户
     */
    private List<Long> determineNotifiedUsers(Long issueId, Long currentUserId) {
        // 这里可以添加更复杂的逻辑
        // 例如：通知需求创建者、处理者、关注者等
        // 简化实现，返回空列表
        return java.util.Collections.emptyList();
    }
}